package main

import (
	"context"
	"gfdemo/common"
	"gfdemo/filter"
	_ "gfdemo/internal/packed"
	"gfdemo/route"

	_ "github.com/gogf/gf/contrib/drivers/pgsql/v2"
	_ "github.com/gogf/gf/contrib/nosql/redis/v2"
	"net/http"

	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
	"github.com/gogf/gf/v2/os/gcmd"
	"github.com/gogf/gf/v2/os/gctx"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/os/gres"
)

func main() {
	Main := gcmd.Command{
		Name:  "main",
		Usage: "main",
		Brief: "start http server of simple goframe demos",
		Func: func(ctx context.Context, parser *gcmd.Parser) (err error) {
			glog.Debugf(ctx, "日志标签: [ %d ]", glog.F_TIME_STD|glog.F_FILE_SHORT)
			// 首先执行 sql 版本迁移
			common.DbMigrate()
			// 加载后台任务管理
			common.LoadTaskMange()
			s := g.Server()
			glog.SetDefaultLogger(s.Logger())
			// 默认的处理异常的拦截器
			s.Use(ghttp.MiddlewareHandlerResponse)
			s.Use(filter.Log)
			s.Use(filter.Error)
			glog.Infof(ctx, "日志标签: [ %d ]", s.Logger().GetConfig().Flags)
			// 当自动生成 url 时，将 UserName 这样的方法转换为 user-name 这样的 url
			// 由于 init 方法在 main 方法之前运行，这个设置要在注册路由之前设置
			s.SetNameToUriType(ghttp.UriTypeDefault)
			s.Group("/", func(group *ghttp.RouterGroup) {
				route.AddRoute(s, group)
			})
			s.BindHookHandlerByMap("/js/*", map[ghttp.HookName]ghttp.HandlerFunc{
				ghttp.HookBeforeServe: filter.HookNoCache,
			})
			s.Start()
			// 使用异步启动，允许有多服务器
			http.ListenAndServe(":8120", nil)
			g.Wait()
			return nil
		},
	}
	gres.Dump()
	Main.Run(gctx.New())
}
